package com.csdj.t309springboot.controller;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

@ServerEndpoint("/ws/test")
@Component
public class WebSocketController {

    private static Set<Session> sessionSet = new HashSet<>();

    @OnOpen
    public void onOpen(Session session) throws IOException {
        sessionSet.add(session);
        System.out.println("创建连接成功 session id:"+session.getId());
        session.getBasicRemote().sendText("hello");
    }

    @OnClose
    public void onClose(Session session){
        System.out.println("关闭连接");
        sessionSet.remove(session);
    }

    @OnError
    public void onError(Session session,Throwable e){

    }
    @OnMessage
    public void onMessage(String msg ,Session session) throws IOException {
        System.out.println("收到消息："+msg);
        sendToAll(msg);
    }

    public void sendToAll(String msg){
        sessionSet.stream().forEach(session -> {
            try {
                if(session.isOpen()){
                    session.getBasicRemote().sendText(msg);
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

}
